import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import ReactHtmlParser from "react-html-parser";
import {
  LeftOutline,
  MessageOutline,
  LikeOutline,
  StarOutline,
  UploadOutline,
} from "antd-mobile-icons";
import "./Detail.less";
import { getNewsInfo, getStoryExtra } from "../../http/api";
// 解析HTML
const parseHtmlContent = (htmlContent) => {
  const parseContent = ReactHtmlParser(htmlContent, {
    transform: (node) => {
      if (node.type == "text") {
        const parseText = ReactHtmlParser(node.data);
        return parseText;
      }
    },
  });
  return parseContent;
};

const Detail = function Detail(props) {
  const { id } = useParams();
  const [detailData, setDetailData] = useState({});
  const [storyExtra, setStoryExtra] = useState({});
  let link;
  let imgPlaceHolder,bigImg;

  useEffect(() => {
    const setDetail = async () => {
      const { data } = await getNewsInfo(id);
      setDetailData(data);
    };
    setDetail();
  }, []);
  useEffect(() => {
    let sendStoryExtra = async () => {
      let {data} = await getStoryExtra(id);
      console.log('data',data)
      setStoryExtra(data);
    };
    sendStoryExtra();
  }, []);
  // 把返回数据中的样式添加进来
  const handleStyle = () => {
    // 创建link
    link = document.createElement("link");
    link.rel = "stylesheet";
    if (detailData.css) {
      link.href = detailData.css[0];
    }

    document.head.appendChild(link);
  };
  // 把返回的顶部大图添加进来
  const handleImg = () => {
    imgPlaceHolder = document.querySelector(".img-place-holder");
    if (imgPlaceHolder) {
      console.log("imgPlaceHolder", imgPlaceHolder);
      bigImg = document.createElement("img");
      bigImg.src = detailData.image;
      imgPlaceHolder.appendChild(bigImg);
    }
  };
  useEffect(() => {
    handleStyle();
    handleImg();
    // 销毁组件：移除创建的样式(眼部每次点击详情都会创建link标签)
    return () => {
      if (link) document.head.removeChild(link);
      if (imgPlaceHolder) imgPlaceHolder.removeChild(bigImg);
    };
  }, [detailData]);
  return (
    <div className="detailPage">
      {parseHtmlContent(detailData.body)}
      {/* 底部按钮 */}
      <div className="tabbar">
        <div
          onClick={() => {
            window.history.back();
          }}
        >
          <LeftOutline fontSize={32} />
        </div>
        <div>
          <MessageOutline fontSize={32} />
          <span>{storyExtra.comments}</span>
        </div>
        <div>
          <LikeOutline fontSize={32} />
          <span>{storyExtra.popularity}</span>
        </div>
        <div>
          <StarOutline fontSize={32} />
        </div>
        <div>
          <UploadOutline fontSize={32} />
        </div>
      </div>
    </div>
  );
};
export default Detail;
